import { Button, message, Divider,Modal,Space } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { PlusOutlined ,ExclamationCircleOutlined} from '@ant-design/icons';
import { queryDepartment, addDepartment, updateDepartment, removeDepartment, queryDepartTree,batchRemoveDepartment } from '@/services/department';
import styles from '@/global.less';
import { useAccess, Access } from 'umi';
const { confirm } = Modal;



/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addDepartment(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateDepartment(fields);
    hide();

    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

//删除单个
const handleRemove = async (departmentId: number) => {
  const hide = message.loading('正在删除');
  try {
    await removeDepartment({ departmentId });
    hide();

    message.success('删除成功，正在刷新！');

    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};

const Department: React.FC = () => {

  const access = useAccess();

  const columns: ProColumns[] = [
    {
      title: '部门名称',
      dataIndex: 'departmentName',

    }, {
      title: '部门描述',
      dataIndex: 'departmentDesc',
      width:400,
    },
    {
      title: '上级名称',
      dataIndex: 'parentName',
    },
    {
      title: '是否启用',
      dataIndex: 'useState',
      valueType: 'radio',
      valueEnum: {
        1: { text: '启用', status: 'Success' },
        0: { text: '禁用', status: 'Error'},
      }
    },
    {
      title: '创建时间',
      search: false,
      dataIndex: 'createTime',
    },
    {
      title: '更新时间',
      search: false,
      dataIndex: 'updateTime',

    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => (
        <>
          <a
            key="editable"
            onClick={async () => {
              queryTreeData();
              handleUpdateModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a onClick={() => {
            confirm({
              title: '您确定要删除吗?',
              icon: <ExclamationCircleOutlined />,
              async onOk() {
                await handleRemove(record.departmentId);
                actionRef.current?.reload();
              },
              onCancel() {
                console.log('Cancel');
              },
            });
          }}
          >
            删除
          </a>
        </>
    )
    },
  ];


  const queryTreeData = async () => {
    let trees = await queryDepartTree({ "type": "root" });
    setTreeData(trees);
  }

  useEffect(() => {
    queryTreeData();
  }, []);

  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const [treeData, setTreeData] = useState<API.TreeNodeItem[]>();
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys,setSelectedRowKeys] = useState<number[]>([]);
  const onSelectChange = async (sKeys ) => {
    setSelectedRowKeys(sKeys);

  };
  
//批量删除
const batchRemove = async () => {

  const hide = message.loading('正在删除');
  try {
    await batchRemoveDepartment({ ids: selectedRowKeys.join(',')});
    setSelectedRowKeys([]);
    hide();
    message.success('删除成功，正在刷新！');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};

  return (
    <>
      <ProTable
        headerTitle=""
        rowKey="departmentId"
        actionRef={actionRef}
       
        toolBarRender={(action, { selectedRows }) => [
          <Access accessible={access.canUpdate} fallback={null}>
            <Button icon={<PlusOutlined />} className={styles.addBtn} type="primary"
              onClick={() => {
                queryTreeData();
                handleModalVisible(true);
              }}>
              新增
            </Button>
          </Access>
        ]}
        options={false}
        request={(params) => queryDepartment(params)}
        columns={columns}
        rowSelection={{selectedRowKeys,onChange: onSelectChange}}
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        tableAlertOptionRender={() => {
          return (
            <Space size={16}>
              <a  onClick={() => {
              confirm({
                title: '您确定要批量删除吗?',
                icon: <ExclamationCircleOutlined />,
                async onOk() {
                  await batchRemove();
                  actionRef.current?.reload();
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }} >批量删除</a>
            
            </Space>
          );
        }}
        pagination={{
          defaultCurrent: 1,
          defaultPageSize: 10,
        }}
      />
      <CreateForm
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        treeData={treeData}
      />
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
          treeData={treeData}
        />
      ) : null}
    </>
  );
};

export default Department;